package ap12.ga1.rocco;
import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class AP12HS4 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			// generating parser
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			// preparing file
			File xmlFile = new File("src/testXML.xml");
			// Building the document
			Document doc = dBuilder.parse(xmlFile);
			// optional, but recommended
			doc.normalize();
			// print the root element
			// System.out.println("Root element : "
			// + doc.getDocumentElement().getNodeName());
			// nList includes house-nodes, so it is the list on the layer of
			// <nebenkosten>
			NodeList nList = doc.getDocumentElement().getElementsByTagName(
					"Haus");
			// iterate over nList (House-objects)
			for (int i = 0; i < nList.getLength(); i++) {
				// nList.item is the House-object
				// System.out.println(nList.item(0).getNodeName());
				// need of the attributes
				NamedNodeMap nMap = nList.item(0).getAttributes();
				// returns the Attribute Id AND Value
				String iD = nMap.getNamedItem("ID").
				// returns only the Element
						getNodeValue();
				// Prints "[knotname]: [first letter of knotname][ID] for the
				// houses
				System.out.println(nList.item(i).getNodeName() + ": "
						+ nList.item(i).getNodeName().substring(0, 1) + iD);
				// need of child nodes of house
				NodeList tempNodeListOfHouse = nList.item(i).getChildNodes();
				double sum = 0;
				for (int j = 0; j < tempNodeListOfHouse.getLength(); j++) {
					// Shortcut for childnode
					Node temp = tempNodeListOfHouse.item(j);
					// am i using valuable childnodes?
					if (temp.getNodeName() != null
							&& !temp.getNodeName().equals("#text")) {
						// Parser for decimal points etc
						java.text.NumberFormat nf = java.text.NumberFormat
								.getNumberInstance();
						// printing
						System.out.println(temp.getNodeName() + ": "
								+ temp.getFirstChild().getNodeValue());
						// adding the costs
						sum = sum
								+ nf.parse(temp.getFirstChild().getNodeValue())
										.doubleValue();
					}

				}
				// Printing the costs
				System.out.println("Haus-Geasmtkosten: " + sum + "\n");
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
